/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package armazemseujose.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author BRUNA
 */
public class listaClientes {

    ArrayList<Cliente> clientes = new ArrayList();

    public listaClientes() throws FileNotFoundException {
        lerArquivoCliente();

    }

    public void add(Cliente c) throws IOException {
        clientes.add(c);
        salvaArquivoCliente(c);

    }
    
    public Cliente procuraCliente(String nome){
        for(Cliente i : clientes){
            if(i.getNome().equalsIgnoreCase(nome)){
                return i;
            }
        }
        return null;
    }

    public void salvaArquivoCliente(Cliente c) throws IOException {
        File dir = new File(".");
        File arq = new File(dir, "clientes.txt");
        FileWriter fileWriter = new FileWriter(arq, true);
        try (PrintWriter printWriter = new PrintWriter(fileWriter)) {
            printWriter.println(c.getNome() + "|" + c.getTelefone() + "|" + c.getEndereco());
            printWriter.flush();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Não foi possível salvar dados do Cliente");
        }
    }
    
    public void lerArquivoCliente() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader("clientes.txt"))
                .useDelimiter("\\||\\n");
        while (scanner.hasNext()) {
            String nome = scanner.next();
            String telefone = scanner.next();
            String end = scanner.next();
            String endereco = end.substring(0, end.length() - 1);
            long i = Long.parseLong(telefone);
            clientes.add(new Cliente(nome, endereco, i));
        }
    }
}
